package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.admin.api.entity.SysDept;
import com.engine4cloud.tdf.admin.api.feign.RemoteDeptService;
import com.engine4cloud.tdf.common.core.constant.SecurityConstants;
import com.engine4cloud.tdf.common.core.constant.enums.DictNameEnum;
import com.engine4cloud.tdf.common.core.constant.enums.WorkerFileTypeEnum;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.core.util.CodeUtils;
import com.engine4cloud.tdf.common.core.util.R;
import com.engine4cloud.tdf.common.core.util.RetOps;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.GzryFunctionaryConvert;
import com.engine4cloud.tdf.supervision.dto.GzryFileDTO;
import com.engine4cloud.tdf.supervision.dto.IdentityUniqueCheckDTO;
import com.engine4cloud.tdf.supervision.dto.MobileUniqueCheckDTO;
import com.engine4cloud.tdf.supervision.dto.create.GzryFunctionaryCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.GzryFileQueryDTO;
import com.engine4cloud.tdf.supervision.dto.query.GzryFunctionaryQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.DictSelectResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.GzryFunctionaryResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.GzryFunctionaryUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.GzryFunctionaryEntity;
import com.engine4cloud.tdf.supervision.mapper.GzryFunctionaryMapper;
import com.engine4cloud.tdf.supervision.service.DictSelectService;
import com.engine4cloud.tdf.supervision.service.GzryFileService;
import com.engine4cloud.tdf.supervision.service.GzryFunctionaryService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 社区矫正工作人员信息采集表
 *
 * @author wenjie
 * @date 2024-04-15 11:37:27
 */
@Service
public class GzryFunctionaryServiceImpl extends ServiceImpl<GzryFunctionaryMapper, GzryFunctionaryEntity> implements GzryFunctionaryService {

    @Resource
    private RemoteDeptService remoteDeptService;

    @Resource
    private GzryFileService fileService;

    @Resource
    private DictSelectService dictSelectService;

    @Override
    public PageInfo<GzryFunctionaryResultDTO> pageList(Params pageable, GzryFunctionaryQueryDTO dto) {
        R<List<Long>> deptIdRemoteList = remoteDeptService.getDescendantIdList(dto.getDeptId(), SecurityConstants.FROM_IN);

        List<Long> deptIdList = RetOps.of(deptIdRemoteList).getData().filter(CollectionUtils::isNotEmpty)
                .orElseThrow(() -> new ValidateCodeException("没有数据权限!"));

        IPage<GzryFunctionaryResultDTO> page = this.baseMapper.pageList(Pages.page(pageable), dto, deptIdList);
        return Pages.convert(page);
    }

    @Override
    public GzryFunctionaryResultDTO getById(Long id) {
        //设置职务
        List<DictSelectResultDTO> positionList = dictSelectService.items(DictNameEnum.POSITION.getType());

        GzryFunctionaryResultDTO result = Optional.ofNullable(GzryFunctionaryConvert.INSTANCE.convert(super.getById(id), positionList))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));
        //设置照片
        List<GzryFileDTO> photoList = fileService.findList(new GzryFileQueryDTO(result.getRybm(), WorkerFileTypeEnum.FUNCTIONARY_PHOTOGRAPH));
        result.setPhotoList(photoList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(GzryFunctionaryCreateDTO dto) {
        Boolean identityUnique = this.checkUniqueByIdentity(new IdentityUniqueCheckDTO(dto.getSfzh()));
        if (!identityUnique) {
            throw new ValidateCodeException("证件号已存在");
        }

        Boolean mobileUnique = this.checkUniqueByMobile(new MobileUniqueCheckDTO(dto.getSj()));
        if (!mobileUnique) {
            throw new ValidateCodeException("手机号已存在");
        }

        TdfUser user = SecurityUtils.getUser();
        //设置所属部门
        SysDept dept = RetOps.of(remoteDeptService.detail(user.getDeptId(), SecurityConstants.FROM_IN)).getData()
                .orElseThrow(() -> new ValidateCodeException("没有数据权限!"));

        GzryFunctionaryEntity entity = GzryFunctionaryConvert.INSTANCE.create(dto, dept, user.getTenantId());
        //设置编号
        entity.setRybm(getFunctionaryCode(user.getDeptId()));
        super.save(entity);
        //设置照片
        fileService.batchSaveFile(new GzryFileQueryDTO(entity.getRybm(), WorkerFileTypeEnum.FUNCTIONARY_PHOTOGRAPH), dto.getPhotoList(), user);
        return true;
    }

    @Override
    public Boolean update(GzryFunctionaryUpdateDTO dto) {
        GzryFunctionaryEntity old = Optional.ofNullable(this.baseMapper.selectById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        Boolean identityUnique = this.checkUniqueByIdentity(new IdentityUniqueCheckDTO(dto.getId(), dto.getSfzh()));
        if (!identityUnique) {
            throw new ValidateCodeException("身份证号已存在");
        }

        Boolean mobileUnique = this.checkUniqueByMobile(new MobileUniqueCheckDTO(dto.getId(), dto.getSj()));
        if (!mobileUnique) {
            throw new ValidateCodeException("手机号已存在");
        }

        //更新主体
        updateById(GzryFunctionaryConvert.INSTANCE.update(dto));
        //更新照片
        fileService.batchUpdateFile(new GzryFileQueryDTO(old.getRybm(), WorkerFileTypeEnum.FUNCTIONARY_PHOTOGRAPH), dto.getPhotoList(), SecurityUtils.getUser());
        return true;
    }

    @Override
    public Boolean checkUniqueByIdentity(IdentityUniqueCheckDTO dto) {
        GzryFunctionaryQueryDTO query = new GzryFunctionaryQueryDTO();
        query.setSfzh(dto.getIdentity());
        Optional<GzryFunctionaryEntity> optional = Optional.ofNullable(getOne(wrapper(query)));
        return optional.map(dx -> Objects.equals(dx.getId(), dto.getId())).orElse(true);
    }

    @Override
    public Boolean checkUniqueByMobile(MobileUniqueCheckDTO dto) {
        GzryFunctionaryQueryDTO query = new GzryFunctionaryQueryDTO();
        query.setSj(dto.getMobile());
        Optional<GzryFunctionaryEntity> optional = Optional.ofNullable(getOne(wrapper(query)));
        return optional.map(dx -> Objects.equals(dx.getId(), dto.getId())).orElse(true);
    }

    /**
     * 获取当前部门下最大的矫正编号
     *
     * @param deptId 部门id
     * @return JzdxCodeGenDTO
     */
    private String getFunctionaryCode(Long deptId) {
        R<SysDept> result = remoteDeptService.detail(deptId, SecurityConstants.FROM_IN);
        SysDept dept = RetOps.of(result)
                .getData()
                .orElseThrow(() -> new ValidateCodeException("部门编码不存在"));

        String deptMaxCode = this.baseMapper.findDeptMaxCode(dept.getOrgCode());

        return CodeUtils.entrustFunctionaryCode(dept.getOrgCode(), deptMaxCode);
    }

    private LambdaQueryWrapper<GzryFunctionaryEntity> wrapper(GzryFunctionaryQueryDTO query) {
        LambdaQueryWrapper<GzryFunctionaryEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(GzryFunctionaryEntity::getId, v));
        Queries.accept(query.getRybm(), v -> wrapper.eq(GzryFunctionaryEntity::getRybm, v));
        Queries.accept(query.getSfzh(), v -> wrapper.eq(GzryFunctionaryEntity::getSfzh, v));
        Queries.accept(query.getSj(), v -> wrapper.eq(GzryFunctionaryEntity::getSjhm, v));
        return wrapper;
    }
}